﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Net;
using System.IO;
using System.Text;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Collections;
using System.Security.Policy;
using Newtonsoft.Json.Linq;

namespace XXX.Common
{
    /// <summary>
    /// http连接基础类，负责底层的http通信
    /// </summary>
    public class HttpService
    {
        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            //直接确认，否则打不开    
            return true;
        }

        //post请求
        /// <summary>
        /// post请求
        /// </summary>
        /// <param name="baseUrl"></param>
        /// <param name="dictbody"></param>
        /// <param name="ContentType"></param>
        /// <param name="dictHead"></param>
        /// <param name="json"></param>
        /// <returns></returns>
        public static string HttpPost(string baseUrl, Dictionary<string, string> dictQueryUrl, string ContentType, Dictionary<string, string> dictbody, Dictionary<string, string> dictHead, string json)
        {
            try
            {
                string result = "";
                if (dictQueryUrl != null && dictQueryUrl.Count > 0)
                {
                    StringBuilder Query = new StringBuilder();
                    baseUrl += "?";
                    int i = 0;
                    foreach (var item in dictQueryUrl)
                    {
                        if (i > 0)
                        {
                            Query.Append("&");
                        }
                        Query.AppendFormat("{0}={1}", item.Key, item.Value);
                        i++;
                    }
                    baseUrl += System.Web.HttpUtility.UrlEncode(Query.ToString());

                }
                //设置最大连接数
                ServicePointManager.DefaultConnectionLimit = 200;
                //设置https验证方式
                if (baseUrl.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback =
                            new RemoteCertificateValidationCallback(CheckValidationResult);


                    ServicePointManager.Expect100Continue = true;
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                    //ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;

                }
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(baseUrl);
                try
                {
                    req.Method = "POST";
                    req.ContentType = ContentType;
                    byte[] data = null;
                    #region 参数
                    StringBuilder builder = new StringBuilder();
                    StringBuilder builder_log = new StringBuilder();
                    if (dictbody != null) //获取token时候参数
                    {
                        int i = 0;
                        foreach (var item in dictbody)
                        {
                            if (i > 0)
                                builder.Append("&");
                            builder.AppendFormat("{0}={1}", item.Key, System.Web.HttpUtility.UrlEncode(item.Value, Encoding.UTF8));
                            builder_log.AppendFormat("{0}={1}", item.Key, item.Value);
                            i++;
                        }
                        data = Encoding.UTF8.GetBytes(builder.ToString());
                    }
                    JObject Head = null;
                    if (dictHead != null && dictHead.Count != 0)//json参数
                    {
                        foreach (var itemon in dictHead)
                        {
                            req.Headers.Add(itemon.Key, itemon.Value);
                        }
                        Head = JObject.FromObject(dictHead);
                    }
                    if (!string.IsNullOrEmpty(json))
                    {
                        data = Encoding.UTF8.GetBytes(json.ToString());
                        ExLog.WriteTxt_JK("【" + baseUrl + "】" + (Head == null ? "" : Head.ToString()) + "发送：" + json.ToString());
                    }
                    else
                    {
                        ExLog.WriteTxt_JK("【" + baseUrl + "】" + (Head == null ? "" : Head.ToString()) + "发送：" + builder_log.ToString());
                    }
                    req.ContentLength = data.Length;
                    using (Stream reqStream = req.GetRequestStream())
                    {
                        reqStream.Write(data, 0, data.Length);
                        reqStream.Close();
                    }
                    #endregion
                    HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                    Stream stream = resp.GetResponseStream();
                    //获取响应内容
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        result = reader.ReadToEnd();
                    }
                    ExLog.WriteTxt_JK("【" + baseUrl + "】接收：" + result);
                    return result;
                }
                catch (Exception ex)
                {
                    ExLog.WriteException(ex.ToString());
                    req = null;
                    return "";
                }
            }
            catch (Exception ex)
            {
                ExLog.WriteException(ex.ToString());
                return "";
            }
        }

        /// <summary>
        /// 处理http GET请求，返回数据
        /// </summary>
        /// <param name="url">请求的url地址</param>
        /// <returns>http GET成功后返回的数据，失败抛WebException异常</returns>
        public static string Get(string url, Dictionary<string, string> dictQueryUrl, Hashtable hst = null)
        {
            System.GC.Collect();
            string result = "";

            HttpWebRequest request = null;
            HttpWebResponse response = null;

            //请求url以获取数据
            try
            {
                if (dictQueryUrl != null && dictQueryUrl.Count > 0)
                {
                    StringBuilder Query = new StringBuilder();

                    int i = 0;
                    foreach (var item in dictQueryUrl)
                    {
                        if (i > 0)
                            Query.Append("&");
                        Query.AppendFormat("{0}={1}", item.Key, item.Value);
                        i++;
                    }
                    url += System.Web.HttpUtility.UrlEncode(Query.ToString());

                }

                //设置最大连接数
                ServicePointManager.DefaultConnectionLimit = 200;

                //设置https验证方式
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback =
                            new RemoteCertificateValidationCallback(CheckValidationResult);
                }

                /***************************************************************
                * 下面设置HttpWebRequest的相关属性
                * ************************************************************/
                request = (HttpWebRequest)WebRequest.Create(url);

                request.Method = "GET";
                if (hst != null && hst.Count > 0)
                {
                    foreach (var item in hst.Keys)
                    {
                        request.Headers.Add(item.ToString(), hst[item.ToString()].ToString());
                    }
                }

                //设置代理
                //WebProxy proxy = new WebProxy();
                //proxy.Address = new Uri(WxPayConfig.PROXY_URL);
                //request.Proxy = proxy;

                //获取服务器返回
                response = (HttpWebResponse)request.GetResponse();

                //获取HTTP返回数据
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                result = sr.ReadToEnd().Trim();
                sr.Close();
            }
            catch (System.Threading.ThreadAbortException e)
            {
                ExLog.WriteTxt("HttpService", "Thread - caught ThreadAbortException - resetting.");
                ExLog.WriteTxt("Exception message", e.Message);
                System.Threading.Thread.ResetAbort();
            }
            catch (WebException e)
            {
                ExLog.WriteTxt("HttpService", e.ToString());
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    ExLog.WriteTxt("HttpService", "StatusCode : " + ((HttpWebResponse)e.Response).StatusCode);
                    ExLog.WriteTxt("HttpService", "StatusDescription : " + ((HttpWebResponse)e.Response).StatusDescription);
                }
                //throw new WxPayException(e.ToString());
            }
            catch (Exception e)
            {
                ExLog.WriteTxt("HttpService", e.ToString());
                //throw new WxPayException(e.ToString());
            }
            finally
            {
                //关闭连接和流
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
            }
            return result;
        }

    }
}